package com.george.shiro.model.service.impl;

import com.george.shiro.config.ShiroRealm;
import com.george.shiro.holder.SpringContextHolder;
import com.george.shiro.model.entity.Resources;
import com.george.shiro.model.entity.User;
import com.george.shiro.model.service.IResourcesService;
import com.george.shiro.model.service.IUserService;
import com.george.shiro.model.service.ShiroService;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author GeorgeChan 2019/5/21 22:25
 * @version 1.0
 * @since jdk1.8
 */
@Slf4j // 打印日志
@Service
public class ShiroServiceImpl implements ShiroService {
    private final IResourcesService resourcesService;
    private final IUserService userService;

    @Autowired
    public ShiroServiceImpl(IResourcesService resourcesService, IUserService userService) {
        this.resourcesService = resourcesService;
        this.userService = userService;
    }

    @Override
    public Map<String, String> loadFilterChainDefinitions() {
        /**
         * 常用的过滤器
         * anon: 无须认证登录，可以访问
         * authc: 必须认证才可以访问
         * user: 如果使用rememberMe功能可以直接访问
         * perms: 该资源必须得到资源权限才可以访问
         * role： 该资源必须得到角色权限才可以访问
         */
        Map<String, String> filterChainDefinitionMap = Maps.newLinkedHashMap();
        // 配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了
        filterChainDefinitionMap.put("/passport/logout", "logout");
        filterChainDefinitionMap.put("/passport/login", "anon");
        filterChainDefinitionMap.put("/passport/signin", "anon");
        filterChainDefinitionMap.put("/favicon.ico", "anon");
        filterChainDefinitionMap.put("/error", "anon");
        filterChainDefinitionMap.put("/assets/**", "anon");
        // 加载数据库中配置的菜单权限列表
        List<Resources> resourcesList = resourcesService.findUrlAndPermision();
        for (Resources resources : resourcesList) {
            if (!Strings.isNullOrEmpty(resources.getPermission())
                    && !Strings.isNullOrEmpty(resources.getUrl())) {
                String permission = "perms[" + resources.getPermission() + "]";
                filterChainDefinitionMap.put(resources.getUrl(), permission);
            }
        }
//        // role的用法
//        filterChainDefinitionMap.put("/admin/**","roles[Admin]");
//        filterChainDefinitionMap.put("/teacher/**","roles[Teacher]");
//        filterChainDefinitionMap.put("/student/**","roles[Student]");
        // 所有资源都必须认证才能操作
        filterChainDefinitionMap.put("/**", "authc");
        return filterChainDefinitionMap;
    }

    @Override
    public void updatePermission() {
        ShiroFilterFactoryBean shirFilter = SpringContextHolder.getBean(ShiroFilterFactoryBean.class);
        synchronized (shirFilter) {
            AbstractShiroFilter shiroFilter;
            try {
                shiroFilter = (AbstractShiroFilter) shirFilter.getObject();
            } catch (Exception e) {
                throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");
            }

            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();

            // 清空老的权限控制
            manager.getFilterChains().clear();

            shirFilter.getFilterChainDefinitionMap().clear();
            shirFilter.setFilterChainDefinitionMap(loadFilterChainDefinitions());
            // 重新构建生成
            Map<String, String> chains = shirFilter.getFilterChainDefinitionMap();
            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ", "");
                manager.createChain(url, chainDefinition);
            }
        }
    }

    @Override
    public void reloadAuthorizingByRoleId(Long roleId) {
        log.info("当前位置 ====》 ShiroServiceImpl  ===》  reloadAuthorizingByRoleId");
        List<User> userList = userService.listByRoleId(roleId);
        if (CollectionUtils.isEmpty(userList)) {
            return;
        }
        for (User user : userList) {
            reloadAuthorizingByUserId(user);
        }
    }

    private void reloadAuthorizingByUserId(User user) {
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        ShiroRealm shiroRealm = (ShiroRealm) rsm.getRealms().iterator().next();
        Subject subject = SecurityUtils.getSubject();
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        SimplePrincipalCollection principals = new SimplePrincipalCollection(user, realmName);
        subject.runAs(principals);
        shiroRealm.getAuthorizationCache().remove(subject.getPrincipals());
        subject.releaseRunAs();

        log.info("用户[{}]的权限更新成功！！", user.getUsername());
    }
}
